<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/notice' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>成绩管理</el-breadcrumb-item>
      <el-breadcrumb-item>成绩查询</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card shadow="never">
      <!-- 消息提示 -->
      <el-alert title="查询条件至少存在一项" type="warning" show-icon class="queryAlert"></el-alert>
      <!-- 添加搜索区域 -->
      <div class="queryBox">
        <!-- 全部搜索条件 -->
        <el-row type="flex" justify="space-between">
          <!-- <el-col :span="2">全部结果：</el-col> -->
          <span class="label">搜索条件：</span>
          <el-col :span="20" :push="2">
            <el-tag
              v-for="(item,index) in queryInfo"
              type="primary"
              :key="index"
              size="medium"
              effect="plain"
              :style="conditionTag[index]"
              @close="clearQuryInfo(index)"
              closable
            >{{item}}</el-tag>
            <!--课程名称输入框 -->
            <el-input
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="mini"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            ></el-input>
            <!-- 显示输入框按钮 -->
            <el-button v-else size="mini" @click="showInput" type="primary">+ 课程名称</el-button>
          </el-col>
        </el-row>
        <!-- 按学院搜索 -->
        <el-row type="flex" justify="space-between">
          <span class="label">学院名称：</span>
          <el-col :span="flag1?17:18" :push="2" :style="'height:'+(flag1?'':'40px')">
            <el-tag
              v-for="(item,index) in collegeData"
              :key="index"
              size="medium"
              effect="plain"
              @click="relevance('college',item.label)"
              class="collegeTag"
            >{{item.label}}</el-tag>
          </el-col>
          <el-col :span="2">
            <el-button
              plain
              size="mini"
              :icon="flag1?'el-icon-caret-top':'el-icon-caret-bottom'"
              @click="flag1=!flag1"
            >{{flag1?'收起':'更多'}}</el-button>
          </el-col>
        </el-row>
        <!-- 按专业搜索 -->
        <el-row type="flex" justify="space-between">
          <span class="label">专业名称：</span>
          <el-col :span="flag3?17:18" :push="2" :style="'height:'+(flag3?'':'40px')">
            <el-tag
              v-for="(item,index) in majors"
              :key="index"
              size="medium"
              effect="plain"
              @click="addQueryInfo('major',item.label)"
              class="majorTag"
            >{{item.label}}</el-tag>
          </el-col>
          <el-col :span="2" v-if="majors.length ===6">
            <el-button
              plain
              size="mini"
              :icon="flag3?'el-icon-caret-top':'el-icon-caret-bottom'"
              @click="flag3=!flag3"
            >{{flag3?'收起':'更多'}}</el-button>
          </el-col>
        </el-row>
        <!-- 按学年搜索 -->
        <el-row type="flex" justify="space-between">
          <span class="label">开课学年：</span>
          <el-col :span="flag2?17:18" :push="2" :style="'height:'+(flag2?'':'40px')">
            <el-tag
              v-for="(item,index) in getYear"
              :key="index"
              size="medium"
              effect="plain"
              @click="addQueryInfo('year',item.label)"
              class="yearTag"
            >{{item.label}}</el-tag>
          </el-col>
          <el-col :span="2">
            <el-button
              plain
              size="mini"
              :icon="flag2?'el-icon-caret-top':'el-icon-caret-bottom'"
              @click="flag2=!flag2"
            >{{flag2?'收起':'更多'}}</el-button>
          </el-col>
        </el-row>
        <!-- 按学期搜索 -->
        <el-row>
          <span class="label">开课学期：</span>
          <el-col :span="8" :push="2">
            <el-radio-group
              size="mini"
              v-model="queryInfo.term"
              @click="addQueryInfo('term',queryInfo.term)"
              @change="queryScore"
            >
              <el-radio label="第一学期" border></el-radio>
              <el-radio label="第二学期" border></el-radio>
            </el-radio-group>
          </el-col>
        </el-row>
      </div>
      <!-- 分割线 -->
      <el-divider class="yearDivider">
        <el-tag v-if="queryInfo.year">{{queryInfo.year}} 学年</el-tag>&nbsp;
        <el-tag v-if="queryInfo.term">{{queryInfo.term}}</el-tag>
      </el-divider>
      <!-- 成绩表格 -->
      <el-table :data="scoreData" border style="width: 100%" stripe class="scoreTab">
        <el-table-column prop="id" label="课程编码"></el-table-column>
        <el-table-column prop="subject" label="课程名称"></el-table-column>
        <el-table-column prop="nature" label="课程性质" width="85"></el-table-column>
        <el-table-column prop="college" label="课程归属"></el-table-column>
        <el-table-column prop="username" label="学生姓名" width="70"></el-table-column>
        <el-table-column prop="major" label="专业名称"></el-table-column>
        <el-table-column prop="final" label="期末" width="50"></el-table-column>
        <el-table-column prop="makeUp" label="补考" width="50"></el-table-column>
        <el-table-column prop="rebuild" label="重修" width="50"></el-table-column>
        <el-table-column prop="credit" label="学分" width="50"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showalterDialog(scope.row._id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="delScore(scope.row._id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改成绩对话框 -->
    <el-dialog title="修改成绩" :visible.sync="alterdialogVisible" width="50%">
      <el-form ref="alterFormRef" :rules="alterRules" :model="studentScore" label-width="100px">
        <el-form-item label="期末成绩:" prop="final">
          <el-input v-model="studentScore.final" type="number"></el-input>
        </el-form-item>
        <el-form-item label="补考成绩:" prop="makeUp">
          <el-input v-model="studentScore.makeUp" type="number"></el-input>
        </el-form-item>
        <el-form-item label="重修成绩:" prop="rebuild">
          <el-input v-model="studentScore.rebuild" type="number"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="alterdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="alterScore">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 存储学院数据
      collegeData: [],
      // 查询条件
      queryInfo: {
        term: '第一学期'
      },
      // 控制学院信息的显示
      flag1: false,
      // 控制学年信息的显示
      flag2: false,
      // 控制专业信息的显示
      flag3: false,
      // 专业集合
      majors: [
        {
          label: '全部专业'
        }
      ],
      conditionTag: {
        term: {
          borderColor: '#51B066',
          color: '#51B066'
        },
        college: {
          borderColor: '#ff9372',
          color: '#ff9372'
        },
        major: {
          borderColor: '#ffe38f',
          color: '#ffe38f'
        },
        year: {
          borderColor: '#73f7e6',
          color: '#73f7e6'
        }
      },
      // 课程名称输入框是否可见
      inputVisible: false,
      // 课程名称输入框值
      inputValue: '',
      // 存储成绩列表
      scoreData: [
        {
          id: '1581216226737',
          subject: '微机系统与原理',
          nature: '公共选修课',
          college: '机械与电气工程学院',
          username: '王小林',
          major: '电气工程及其自动化',
          final: 58,
          makeUp: 59,
          rebuild: 60,
          credit: 1.5
        }
      ],
      // 存储单个学生成绩
      studentScore: {},
      // 控制修改成绩对话框是否可见
      alterdialogVisible: false,
      // 修改成绩表单的验证规则
      alterRules: {
        final: [
          {
            required: true,
            message: '请输入期末成绩，必须为数字',
            trigger: 'blur'
          },
          { min: 1, max: 3, message: '不能超过三位数字', trigger: 'blur' }
        ],
        makeUp: [
          {
            required: true,
            message: '请输入补考成绩，必须为数字',
            trigger: 'blur'
          },
          { min: 1, max: 3, message: '不能超过三位数字', trigger: 'blur' }
        ],
        rebuild: [
          {
            required: true,
            message: '请输入重修成绩，必须为数字',
            trigger: 'blur'
          },
          { min: 1, max: 3, message: '不能超过三位数字', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 获取学院列表
    async getCollegeList() {
      let res = await this.$http.get('colleges')
      // 获取学院列表失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取学院列表失败')
      }
      // 获取学院列表成功
      this.collegeData = res.data
    },
    // 获取专业列表
    async getMajorList(college) {
      let res = await this.$http.get('/colleges/majors', {
        params: { college }
      })
      // 获取专业列表失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取专业列表失败')
      }
      // 获取专业列表成功
      this.majors = res.data.children
    },
    relevance(label, value) {
      // 添加查询条件
      this.addQueryInfo(label, value)
      // 更新专业列表
      this.getMajorList(value)
    },
    // 添加查询条件
    addQueryInfo(label, value) {
      // 添加查询对象中的条件属性
      this.queryInfo[label] = value
      // 刷新页面
      this.$forceUpdate()
      // 发起成绩查询
      this.queryScore()
    },
    // 移除查询条件
    clearQuryInfo(label) {
      // 获取查询对象中，条件属性的个数
      let len = Object.getOwnPropertyNames(this.queryInfo).length - 1
      // 如果搜索条件只剩一项,不再清除直接返回
      if (len === 1) return
      // 删除查询对象中的条件属性
      delete this.queryInfo[label]
      // 刷新页面
      this.$forceUpdate()
      // 发起成绩查询
      this.queryScore()
    },
    // 课程名称输入框显示时触发
    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框失去焦点或回车时触发
    handleInputConfirm() {
      let inputValue = this.inputValue
      if (inputValue) {
        this.addQueryInfo('subject', inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    },
    // 查询学生成绩
    async queryScore() {
      // 深拷贝查询数据对象
      let queryInfo = _.cloneDeep(this.queryInfo)
      // 格式化学期属性
      if (queryInfo.term) {
        queryInfo.term = queryInfo.term === '第一学期' ? 1 : 2
      }
      // 格式化专业属性
      if (queryInfo.major) {
        queryInfo.major =
          queryInfo.major === '全部专业' ? null : queryInfo.major
      }
      // 发起请求
      let res = await this.$http.get('/scores', { params: queryInfo })
      // 查询失败,直接返回
      if (res.meta.status !== 200) {
        return this.$message.error('学生成绩查询失败')
      }
      // 查询成功
      this.scoreData = res.data
    },
    // 删除成绩
    async delScore(id) {
      let result = await this.$confirm(
        '此操作将永久删除该学生成绩, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(() => {
        this.$message.info('已取消删除')
      })

      if (result === 'confirm') {
        // 发起删除请求
        let res = await this.$http.delete('scores', { params: { id } })
        // 删除失败
        if (res.meta.status !== 204) {
          return this.$message.error('删除失败')
        }
        // 删除成功
        this.$message.success('删除成功!')
        // 刷新列表
        this.queryScore()
      }
    },
    // 获取学生成绩
    async getStudentScore(id) {
      let res = await this.$http.get('scores/student', { params: { id } })
      // 获取失败
      if (res.meta.status !== 200) {
        return this.$message.error('获取学生成绩失败')
      }
      // 获取学生成绩成功
      this.studentScore = res.data
    },
    // 显示修改对话框
    showalterDialog(id) {
      // 获取学生成绩
      this.getStudentScore(id)
      // 打开对话框
      this.alterdialogVisible = true
    },
    // 修改学生成绩
    alterScore() {
      this.$refs.alterFormRef.validate(async valid => {
        // 验证失败直接返回
        if (!valid) return
        // 验证成功，发起请求
        let res = await this.$http.put('scores', this.studentScore)
        // 获取失败
        if (res.meta.status !== 201) {
          return this.$message.error('修改学生成绩失败')
        }
        // 修改学生成绩成功
        this.$message.success('修改学生成绩成功')
        // 刷新页面
        this.queryScore()
        // 关闭修改对话框
        this.alterdialogVisible = false
      })
    }
  },
  created() {
    // 获取学院列表
    this.getCollegeList()
    // 查询学生成绩
    this.queryScore()
  },
  computed: {
    // 创建学年范围
    getYear() {
      let years = []
      let current = new Date()
      let year = current.getFullYear() - 4

      for (let i = 0; i < 8; i++) {
        let obj = {}
        obj.label = [year + i, year + i + 1].join(' - ')
        years.push(obj)
      }
      return years
    }
  }
}
</script>

<style lang="less" scoped>
.queryAlert {
  margin-bottom: 10px;
}
.queryBox {
  .el-row {
    line-height: 40px;
    font-size: 13px;
    position: relative;
    .label {
      position: absolute;
      left: 0;
      color: #666;
    }
    .el-col {
      overflow: hidden;
    }
    .el-tag {
      margin-right: 10px;
    }
    .collegeTag {
      border-color: #ff9372;
      color: #ff9372;
    }
    .collegeTag:hover {
      cursor: pointer;
      background-color: #fddfd2;
    }
    .majorTag {
      border-color: #ffe38f;
      color: #ffe38f;
    }
    .majorTag:hover {
      cursor: pointer;
      background-color: #fdfbed;
    }
    .yearTag {
      border-color: #73f7e6;
      color: #73f7e6;
    }
    .yearTag:hover {
      cursor: pointer;
      background-color: #d3fafe;
    }

    .el-radio {
      margin: 0;
    }
  }
}
.yearDivider {
  margin: 50px 0;
}
</style>